import "dotenv/config";
import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  baseURL: process.env.OPENAI_API_BASE,
});

function getCurrentWeather({ location, unit = "fahrenheit" }) {
  const weather_info = {
    location: location,
    temperature: "72",
    unit: unit,
    forecast: ["sunny", "windy"],
  };
  return JSON.stringify(weather_info);
}

const tools = [
  {
    type: "function",
    function: {
      name: "getCurrentWeather",
      description: "Get the current weather in a given location",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "The city and state, e.g. San Francisco, CA",
          },
          unit: { type: "string", enum: ["celsius", "fahrenheit"] },
        },
        required: ["location"],
      },
    },
  },
];

const messages = [{ role: "user", content: "北京天气如何?" }];

const result = await openai.chat.completions.create({
  model: "gpt-3.5-turbo",
  messages,
  tools,
});

messages.push(result.choices[0].message);

const functions = {
  getCurrentWeather: getCurrentWeather,
};

const cell = result.choices[0].message.tool_calls[0];
const functionInfo = cell.function;
const functionName = functionInfo.name;
const functionParams = functionInfo.arguments;
const functionResult = functions[functionName](functionParams);

messages.push({
  tool_call_id: cell.id,
  role: "tool",
  name: functionName,
  content: functionResult,
});

const response = await openai.chat.completions.create({
  model: "gpt-3.5-turbo",
  messages,
});
console.log(response.choices[0].message);
